import tkinter as tk
from tkinter import ttk
from tkinter import Menu
import os
import subprocess

win = tk.Tk()
win.title("Kahn Software v1")    # #窗口标题
win.geometry("600x500+200+20")   # #窗口位置500后面是字母x

my_data = [
    {"文件名": 50,
     "大小" : 50,
     "路径" : 100,
    },
    {"文件名": "k1n",
     "大小" : 12,
     "路径" : "C:\\Users\\user\\Desktop\\514table\\generationConfig.xml",
    },
    {"文件名": "k1n",
    "大小" : 12,
    "路径" : "C:\\Users\\user\\Desktop\\514table\\generationConfig.xml",
    },
    {"文件名": "k1n",
    "大小" : 12,
    "路径" : "C:\\Users\\user\\Desktop\\514table\\generationConfig.xml",
    },
]

# 打开目录
def open_directory_with_event(evet):
    open_directory()
def open_directory():
    item = tree.selection()[0]  # 获取选中的项
    if os.path.exists(tree.item(item, 'values')[2]):
        subprocess.run(['explorer', '/select,', tree.item(item, 'values')[2]], shell=True)

# 创建tree
def getMyTree(data, window):
    tree = ttk.Treeview(window)      # #创建表格对象 
    tree["columns"] = tuple(data[0].keys())     # #定义列
    for name in data[0]:
        tree.column(name, width=data[0][name])          # #设置列
        tree.heading(name, text=name)        # #设置显示的表头名

    # 隐藏第一列
    tree.column('#0', width=0, stretch=tk.NO) 
    # 插入数据
    for (index, item) in enumerate(data):
        if index == 0:
            continue
        tree.insert("",index+1, text=index+1, values=tuple(item.values()))

    # 右键菜单
    menu = Menu(window, tearoff=0)
    menu.add_command(label="Open", command=open_directory)
    menu.add_command(label="Delete", command=lambda: print("Delete"))
    # 创建右键菜单
    def callback(event):
        menu.post(event.x_root, event.y_root)
    # 绑定右键事件
    tree.bind('<Button-3>', callback)

    return tree

tree = getMyTree(my_data, win)
tree.bind('<Double-1>', open_directory_with_event)
tree.pack()
win.mainloop()